import * as fs from 'fs';
import * as dotenv from 'dotenv';
import { queryItems } from './mongoClient';
import getPatentAnalysis from './aiForPatents';
import { removeDivTags, getFormattedDate, getEnv, convertToUnixTimestamp } from './utils';
import { getAccessToken, addRecords } from './wecom';

dotenv.config();

const legalStatusMapping: { [key: number]: string } = {
    1: '公开',
    2: '实质审查',
    3: '授权'
};

interface PatentData {
    申请号: { type: string; text: string; }[];
    专利名称: { type: string; text: string; }[];
    专利摘要: { type: string; text: string; }[];
    申请公司: { type: string; text: string; }[];
    法律状态: { type: string; text: string; }[];
    申请日?: any;
    首次公开日?: any;
    授权日?: any;
}

interface Patent {
    patentId: string;
    no: string;
    title: string;
    abst: string;
    ancs: string;
    apd: string;
    fpbd: string;
    isd: string;
    leagal: string;
}

type LegalStatus = '公开' | '实质审查' | '授权';

function transformData(data: any): Patent {
    return {
        patentId: data.PATENT_ID,
        no: data.PN,
        title: data.TITLE,
        abst: removeDivTags(data.ABST),
        ancs: data.ANCS.join(', '),
        apd: data.APD,
        fpbd: data.F_PBD !== undefined ? data.F_PBD : '无',
        isd: data.ISD,
        leagal: legalStatusMapping[data.LEGAL_STATUS[0]]
    };
}

interface PatentGroup {
    [key: string]: Patent[];
}

const groupByLeagal = (patents: Patent[]): PatentGroup => {
    return patents.reduce((groups, patent) => {
        const leagal = patent.leagal;
        if (!groups[leagal]) {
            groups[leagal] = [];
        }
        groups[leagal].push(patent);
        return groups;
    }, {} as { [key: string]: Patent[] });
};

async function generateMarkdown(patents: Patent[], analytics: Record<LegalStatus, number>, regionConf: string): Promise<string> {
    const records = patents.map(patent => {
        let params: PatentData = {
            "申请号": [{ type: "text", text: patent.no }],
            "专利名称": [{ type: "text", text: patent.title }],
            "专利摘要": [{ type: "text", text: patent.abst }],
            "申请公司": [{ type: "text", text: patent.ancs }],
            "法律状态": [{ type: "text", text: patent.leagal }]
        };
        if (patent.apd) params["申请日"] = convertToUnixTimestamp(patent.apd).toString();
        if (patent.fpbd) params["首次公开日"] = convertToUnixTimestamp(patent.fpbd).toString();
        if (patent.isd) params["授权日"] = convertToUnixTimestamp(patent.isd).toString();
        return { values: params };
    });

    const token = await getAccessToken(getEnv('CORPID'), getEnv('CORPSECRET'));
    let sheetId = regionConf === '国外' ? getEnv('GUOWAI_SHEET_ID') : getEnv('GUONEI_SHEET_ID');
    await addRecords(token, getEnv('DOCID'), sheetId, records);

    let markdown = `---\ntitle: ${regionConf}公司近7日专利-${getFormattedDate('YYYY年MM月DD日')}\ntags: ${regionConf}专利\ndate: ${getFormattedDate('YYYY年MM月DD日 hh:mm:ss')}\n---\n
| **状态** | **数量** |
|----------|-----------|
| 公开     | ${analytics["公开"]} |
| 审查     | ${analytics["实质审查"]} |
| 授权     | ${analytics["授权"]} |
| 总计     | ${patents.length} |
    \n\n`;

    const completion = await getPatentAnalysis(regionConf);
    markdown += `\n **AI趋势分析** ： ${completion.choices[0].message.content}\n\n`;

    const patentGroups = groupByLeagal(patents);
    for (const [legal, patentList] of Object.entries(patentGroups)) {
        markdown += `### ${legal} (${patentList.length}条)\n`;

        // 按申请公司分组
        const companyGroups = patentList.reduce((groups, patent) => {
            const company = patent.ancs || '未知公司';
            if (!groups[company]) {
                groups[company] = [];
            }
            groups[company].push(patent);
            return groups;
        }, {} as { [key: string]: Patent[] });

        for (const [company, companyPatentList] of Object.entries(companyGroups)) {
            markdown += `#### 申请公司：${company} (${companyPatentList.length}条)\n`;

            companyPatentList.forEach((patent, index) => {
                markdown += `##### [${index + 1}. ${patent.title}](https://analytics.zhihuiya.com/patent-view/abst?patentId=${patent.patentId})\n\n`;
                markdown += `**申请号**: ${patent.no}\n\n`;
                markdown += `**专利摘要**: ${patent.abst ? patent.abst : '暂无'}\n\n`;
                markdown += `**申请日**: ${patent.apd}\n\n`;
                markdown += `**首次公开日**: ${patent.fpbd}\n\n`;
                markdown += `**授权日**: ${patent.isd ? patent.isd : '暂无'}\n\n`;
                markdown += `**法律状态**: **${patent.leagal}**\n\n`;
                markdown += `---\n\n`;
            });
        }
    }

    return markdown;
}

async function queryPatents(regionConf: string) {
    const now = new Date();
    const sevenDaysAgo = new Date(now);
    sevenDaysAgo.setDate(now.getDate() - 7);

    const query = {
        region: regionConf,
        WS_CREATED_AT: {
            $gte: sevenDaysAgo.toISOString(),
            $lt: now.toISOString()
        }
    };

    const analytics: Record<LegalStatus, number> = {
        '公开': 0,
        '实质审查': 0,
        '授权': 0
    };

    const transformedItems = await Promise.all((await queryItems(query)).map(async item => {
        const transformedItem = transformData(item);
        const legalStatus = transformedItem.leagal as LegalStatus;
        if (legalStatus in analytics) {
            analytics[legalStatus] += 1;
        }
        return transformedItem;
    }));
    const markdown = await generateMarkdown(transformedItems, analytics, regionConf);
    const fileName = regionConf === '国外' ? `source/_posts/gwzl${getFormattedDate()}.md` : `source/_posts/gnzl${getFormattedDate()}.md`;
    fs.writeFileSync(fileName, markdown, 'utf-8');
}

async function main() {
    for (const region of ['国内', '国外']) {
        await queryPatents(region);
    }
}

if (require.main === module) {
    main().catch(console.error);
}
